package client.comm.commlib.comm_ui

import android.Manifest
import android.content.*
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Environment.getExternalStorageDirectory
import android.provider.MediaStore
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.EnvironmentCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import androidx.loader.app.LoaderManager
import androidx.loader.content.CursorLoader
import androidx.loader.content.Loader
import androidx.recyclerview.widget.GridLayoutManager
import client.comm.commlib.R
import client.comm.commlib.comm_ui.adapter.ImageAdapter
import client.comm.commlib.comm_ui.adapter.ImageFolderAdapter
import client.comm.commlib.comm_ui.bean.Image
import client.comm.commlib.comm_ui.bean.ImageFolder
import client.comm.commlib.comm_ui.bean.SelectOptions
import client.comm.commlib.comm_ui.draw.SpaceGridItemDecoration
import client.comm.commlib.comm_ui.draw.SpacePblGridItemDecoration
import client.comm.commlib.comm_ui.popu.ImageFolderPopupWindow
import client.comm.commlib.databinding.ActivitySelectphotoBinding
import client.comm.commlib.dipToPx
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.Util
import com.bumptech.glide.Glide
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

class SelectPhotoActivity : AppCompatActivity(),
    EasyPermissions.PermissionCallbacks {
    private val RC_CAMERA_PERM = 0x03
    private val RC_EXTERNAL_STORAGE = 0x04
    lateinit var binding: ActivitySelectphotoBinding
    val mCursorLoader: LoaderManager.LoaderCallbacks<Cursor> by lazy {

        object : LoaderManager.LoaderCallbacks<Cursor> {

            private val IMAGE_PROJECTION = arrayOf(
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media._ID,
                MediaStore.Images.Media.MINI_THUMB_MAGIC,
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME
            )

            override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> {
                //数据库光标加载器
                return CursorLoader(
                    this@SelectPhotoActivity,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION,
                    null, null, IMAGE_PROJECTION[2] + " DESC"
                )
            }

            override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor?) {
                if (data != null) {
                    val images = ArrayList<Image>()

                    val imageFolders: MutableList<ImageFolder?> = ArrayList()
                    val defaultFolder = ImageFolder()
                    defaultFolder.name = "全部照片"
                    val count = data.count
                    var index = -1
                    if (count > 0) {
                        data.moveToFirst()
                        do {
                            val path =
                                data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]))

                            if (!File(path).exists()) {
                                continue
                            }
                            val name =
                                data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]))
                            val dateTime =
                                data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]))
                            val id = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[3]))
                            val thumbPath =
                                data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[4]))
                            val bucket =
                                data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[5]))
                            val imgUri = ContentUris.withAppendedId(
                                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                id
                            )

                            if (defaultFolder.imgUri == null) {
                                defaultFolder.imgUri = (imgUri)
                                imageFolders.add(defaultFolder)
                            }
                            val image = Image()
                            image.path = (path)
                            image.name = (name)
                            image.date = (dateTime)
                            image.id = (id)

                            image.imgUri = (imgUri)
                            image.thumbPath = (thumbPath)
                            image.folderName = (bucket)
                            images.add(image)

                            if (imageUri != null && imageUri == imgUri) {
//                                mSelectedImage.add(image)
                                index = images.indexOf(image)
                            }
                            //如果是被选中的图片
                            if (mSelectedImage.size > 0) {
                                for (i in mSelectedImage) {
                                    if (i.path.equals(image.path)) {
                                        image.isSelect = (true)
                                    }
                                }
                            }
                            val imageFile = File(path)
                            val folderFile = imageFile.parentFile
                            val folder = ImageFolder()
                            folder.name = (folderFile.name)
                            folder.path = (folderFile.absolutePath)
                            if (!imageFolders.contains(folder)) {
                                folder.images.add(image)
                                folder.albumPath = (image.path) //默认相册封面
                                folder.imgUri = (image.imgUri)
                                imageFolders.add(folder)
                            } else {
                                // 更新
                                val f = imageFolders[imageFolders.indexOf(folder)]
                                f!!.images.add(image)
                            }
                        } while (data.moveToNext())
                    }
                    defaultFolder.images.addAll(images)
                    addImagesToAdapter(images)
                    if (mOption != null && mOption!!.hasCam) {
                        defaultFolder.albumPath =
                            (if (images.size > 1) images[1].path else "")
                    } else {
                        defaultFolder.albumPath = (if (images.size > 0) images[0].path else "")
                    }
                    mImageFolderAdapter.resetItem(imageFolders)

                    //删除掉不存在的，在于用户选择了相片，又去相册删除
                    if (mSelectedImage.size > 0) {
                        val rs: MutableList<Image> = ArrayList()
                        for (i in mSelectedImage) {
                            val f: File = File(i.path)
                            if (!f.exists()) {
                                rs.add(i)
                            }
                        }
                        mSelectedImage.removeAll(rs)
                    }
                    if (index > 0) {
//                                mSelectedImage.add(image)
                        handleSelectChange(index)
                    }
                    // If add new mCamera picture, and we only need one picture, we result it.
//                if (mOption.mSelectCount == 1 && imageUri != null) {
//
//                    handleSelectChange()
//                    handleResult();
//                }

                    //handleSelectSizeChange(mSelectedImage.size());
                }
            }

            override fun onLoaderReset(loader: Loader<Cursor>) {
                TODO("Not yet implemented")
            }

        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (getLayout() > 0) {
            binding = DataBindingUtil.setContentView(this, getLayout())
            binding.lifecycleOwner = this
        }
        initView()
        lifecycleScope.launchWhenCreated { }
    }


    fun getLayout(): Int {
        return R.layout.activity_selectphoto
    }

    companion object {
        var mOption: SelectOptions? = null
        fun show(context: Context, options: SelectOptions) {
            mOption = options
            context.startActivity(Intent(context, SelectPhotoActivity::class.java))
        }
    }


    private val mSelectedImage: MutableList<Image> by lazy { ArrayList<Image>() }

    private val mFolderPopupWindow: ImageFolderPopupWindow by lazy {
        val popupWindow = ImageFolderPopupWindow(this, object : ImageFolderPopupWindow.Callback {
            override fun onSelect(popupWindow: ImageFolderPopupWindow, model: ImageFolder) {
                addImagesToAdapter(model.images)
                binding.rvImage.scrollToPosition(0)
                popupWindow.dismiss()
                binding.btnTitleSelect.text = model.name
            }

            override fun onDismiss() {
                binding.ivTitleSelect.setImageResource(R.mipmap.ic_arrow_bottom)
            }

            override fun onShow() {
                binding.ivTitleSelect.setImageResource(R.mipmap.ic_arrow_top)
            }
        })
        popupWindow.setAdapter(mImageFolderAdapter)
        popupWindow
    }
    private val mImageFolderAdapter: ImageFolderAdapter by lazy {
        ImageFolderAdapter(this, Glide.with(this))
    }

    private val mImageAdapter: ImageAdapter by lazy {
        if (mOption == null) {
            finish()
        }

        val mImageAdapter = ImageAdapter(this, Glide.with(this))
        mOption?.let {
            mImageAdapter.setSingleSelect(it.mSelectCount <= 1)
            mImageAdapter.setOnItemClickListener(object : ImageAdapter.OnItemClickListener {
                override fun onItemClick(position: Int) {
                    if (it.hasCam) {
                        if (position != 0) {
                            handleSelectChange(position);
                        } else {
                            if (mSelectedImage.size < it.mSelectCount) {
                                requestCamera();
                            } else {
                                toast("最多只能选择 " + it.mSelectCount + " 张图片")
                            }
                        }
                    } else {
                        handleSelectChange(position);
                    }
                }
            });
        }
        mImageAdapter
    }

    private fun handleSelectChange(position: Int) {
        if (mOption == null) return
        val image = mImageAdapter.getItems().get(position) ?: return
        //如果是多选模式
        val selectCount: Int = mOption!!.mSelectCount
        if (selectCount > 1) {
            if (image.isSelect) {
                image.isSelect = (false)
                mSelectedImage.remove(image)
                mImageAdapter.updateItem(position)
            } else {
                if (mSelectedImage.size == selectCount) {
                    toast("最多只能选择 $selectCount 张照片")
                } else {
                    image.isSelect = true
                    mSelectedImage.add(image)
                    mImageAdapter.updateItem(position)
                }
            }
            handleSelectSizeChange(mSelectedImage.size)
        } else {
            mSelectedImage.add(image)
            handleResult()
        }
    }

    fun initView() {
        binding.event = this

        if (mOption == null) {
            finish()
        }
        binding.rvImage.setAdapter(mImageAdapter)
        binding.rvImage.setLayoutManager(GridLayoutManager(this, 4))
        binding.rvImage.addItemDecoration(
            SpaceGridItemDecoration(
                dipToPx(
                    resources, 1f
                ).toInt(),
            )
        )
        if (mOption!!.mSelectCount == 1)
            binding.btnPreview.visibility = View.GONE
        requestExternalStorage()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    fun previewClick() {
        if (mSelectedImage.size > 0) {
            val intent = Intent(this, ImageGalleryActivity::class.java)
            intent.putExtra("isLocal", true)
            intent.putParcelableArrayListExtra(
                ImageGalleryActivity.KEY_IMAGE, Util.toArray(
                    mSelectedImage
                )
            )
            intent.putExtra(ImageGalleryActivity.KEY_NEED_SAVE, false)
            startActivity(intent)
        }
    }

    fun doneClick() {
        handleResult()
    }

    private fun handleSelectSizeChange(size: Int) {
        if (size > 0) {
            binding.btnPreview.setEnabled(true)
            binding.btnDone.setEnabled(true)
            binding.btnDone.setText(String.format("%s(%s)", "完成", size))
        } else {
            binding.btnPreview.setEnabled(false)
            binding.btnDone.setEnabled(false)
            binding.btnDone.setText("完成")
        }
    }

    private fun addImagesToAdapter(images: MutableList<Image>) {
        mOption?.let {
            if (it.hasCam) {//显示拍照按钮
                if (images != null) {
                    if (images.size > 0) {
                        if (images[0].id != 0.toLong()) {
                            val cam = Image()
                            images.add(0, cam)
                        }
                    } else {
                        val cam = Image()
                        images.add(0, cam)
                    }
                }
            }
            mImageAdapter.resetItem(images)
        }
    }

    private fun handleResult() {
        if (mSelectedImage.size != 0) {
            mOption!!.mCallback
                .doSelected(Util.toArray(mSelectedImage))
            finish()
        } else {
            toast("请选择后再操作")
        }
    }


    fun requestCamera() {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
            toOpenCamera()
        } else {
            EasyPermissions.requestPermissions(
                this,
                "",
                RC_CAMERA_PERM,
                Manifest.permission.CAMERA
            )
        }
    }

    private var imageUri: Uri? = null

    /**
     * 打开相机
     */
    private fun toOpenCamera() {
//        val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
//        if (captureIntent.resolveActivity(packageManager) != null) {
//            var photoFile: File? = null
//            var photoUri: Uri? = null
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//                // 适配android 10
//                photoUri = createImageUri()
//            } else {
//                try {
//                    photoFile = createImageFile()
//                } catch (e: IOException) {
//                    e.printStackTrace()
//                }
//                if (photoFile != null) {
//
//                    photoUri =
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //7.0到9.0
//                            //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri 如：content://
//                            FileProvider.getUriForFile(
//                                this,
//                                packageName + ".provider", photoFile
//                            )
//                        } else { //7.0以下, 如：file://
//                            Uri.fromFile(photoFile)
//                        }
//                }
//            }
//
//            imageUri = photoUri
//            if (photoUri != null) {
//                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
//                    val resInfoList: List<ResolveInfo> = packageManager
//                        .queryIntentActivities(captureIntent, PackageManager.MATCH_DEFAULT_ONLY)
//                    for (resolveInfo in resInfoList) {
//                        val packageName: String = resolveInfo.activityInfo.packageName
//                        grantUriPermission(
//                            packageName, photoUri,
//                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
//                        )
//                    }
//                }
//                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
//                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
//                startActivityForResult(captureIntent, 0x03)
//            }
//        }

        //--------------------------
        //--------------------------
        //设置参数
        //--------------------------
        //--------------------------
        //设置参数
        imageUri = createImageUri()

//		设置保存参数到ContentValues中
        //		设置保存参数到ContentValues中
//        val contentValues = ContentValues()
//        //设置文件名
//        //设置文件名
//
//        //兼容Android Q和以下版本
//        //兼容Android Q和以下版本
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//            //android Q中不再使用DATA字段，而用RELATIVE_PATH代替
//            //RELATIVE_PATH是相对路径不是绝对路径
//            //DCIM是系统文件夹，关于系统文件夹可以到系统自带的文件管理器中查看，不可以写没存在的名字
//            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/Pictures")
//        } else {
//
//            val fileDir = createImageFile()
//            if (fileDir != null && fileDir.exists()) {
//
//                //Android Q以下版本
//                fileDir?.let {
//                    contentValues.put(MediaStore.Images.Media.DATA, it.absolutePath)
//                }
//            } else {
//                toast("失败")
//                return
//            }
//        }
        //设置文件类型
        //设置文件类型
//        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG")
        //执行insert操作，向系统文件夹中添加文件
        //EXTERNAL_CONTENT_URI代表外部存储器，该值不变
        //执行insert操作，向系统文件夹中添加文件
        //EXTERNAL_CONTENT_URI代表外部存储器，该值不变
//        uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
//        若生成了uri，则表示该文件添加成功
        //        若生成了uri，则表示该文件添加成功

        if (imageUri == null) {
            toast("拍照失败")
            return
        }
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
        startActivityForResult(intent, 0x03)

    }

    @Throws(IOException::class)
    private fun createImageFile(): File? {
        val imageName = SimpleDateFormat(
            "yyyyMMdd_HHmmss",
            Locale.getDefault()
        ).format(Date()).toString() + ".jpg"
        //        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//        File storageDir = Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_PICTURES);
        val storageDir = File(
            getExternalStorageDirectory().absolutePath
                    + File.separator + "Pictures" + File.separator + "abc"
        )
        if (!storageDir.exists()) storageDir.mkdirs()
        val tempFile = File(storageDir, imageName)
        return if (Environment.MEDIA_MOUNTED != EnvironmentCompat.getStorageState(tempFile)) {
            null
        } else tempFile
    }


    fun titleSelectClick() {
        mFolderPopupWindow.showAsDropDown(binding.toolbar)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            0x03 -> {
                if (resultCode == RESULT_CANCELED)
                    imageUri?.let {
                        val path = it.path
                        val id = path!!.substring(path!!.lastIndexOf("/") + 1)

                        contentResolver.delete(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            MediaStore.Images.Media._ID + " = ?",
                            arrayOf(id)
                        )
                    }
                else {
                    LoaderManager.getInstance(this).restartLoader<Cursor>(0, null, mCursorLoader)
                }
            }
        }
    }

    fun createImageUri(): Uri? {
//        val values = ContentValues()
//        // 需要指定文件信息时，非必须
//        values.put(MediaStore.Images.Media.DESCRIPTION, "This is an image")
//        values.put(
//            MediaStore.Images.Media.DISPLAY_NAME,
//            System.currentTimeMillis().toString() + ".jpg"
//        )
//        values.put(MediaStore.Images.Media.TITLE, System.currentTimeMillis().toString() + ".jpg")
//        values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/albumCameraImg")
//        return getContentResolver()
//            .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)

        //设置保存参数到ContentValues中

        //设置保存参数到ContentValues中
        val contentValues = ContentValues()
        //设置文件名
        //设置文件名
        contentValues.put(
            MediaStore.Images.Media.DISPLAY_NAME,
            System.currentTimeMillis().toString() + ""
        )
        //兼容Android Q和以下版本
        //兼容Android Q和以下版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            //android Q中不再使用DATA字段，而用RELATIVE_PATH代替
            //TODO RELATIVE_PATH是相对路径不是绝对路径;照片存储的地方为：内部存储/Pictures/preventpro
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/preventpro")
        } else {
            val fileDir = createImageFile()
            if (fileDir != null) {
                contentValues.put(MediaStore.Images.Media.DATA, fileDir.absolutePath)
            } else {
                return null
            }
        }
        //设置文件类型
        //设置文件类型
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG")
        //执行insert操作，向系统文件夹中添加文件
        //EXTERNAL_CONTENT_URI代表外部存储器，该值不变
        //执行insert操作，向系统文件夹中添加文件
        //EXTERNAL_CONTENT_URI代表外部存储器，该值不变
        return contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)

    }

    fun requestExternalStorage() {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            LoaderManager.getInstance(this).initLoader<Cursor>(0, null, mCursorLoader)
        } else {
            EasyPermissions.requestPermissions(
                this,
                "",
                RC_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        when (requestCode) {
            RC_CAMERA_PERM -> {
                toOpenCamera()
            }
            RC_EXTERNAL_STORAGE -> {
                LoaderManager.getInstance(this).initLoader<Cursor>(0, null, mCursorLoader)
            }
        }
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        when (requestCode) {
            RC_CAMERA_PERM -> {
                AppSettingsDialog.Builder(this)
                    .setRationale("没有权限, 你需要去设置中开启相机权限")
                    .setNegativeButton("取消")
                    .setPositiveButton("去设置")
                    .build().show()
            }
            RC_EXTERNAL_STORAGE -> {
                AppSettingsDialog.Builder(this)
                    .setRationale("没有权限, 你需要去设置中开启读取手机存储权限")
                    .setNegativeButton("取消")
                    .setPositiveButton("去设置")
                    .build().show()
            }
        }
    }
}